package com.mq.dialogdemo.custom;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.mq.dialogdemo.R;

public class CustomActivity extends AppCompatActivity {
    private static final String TAG = CustomActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);

        View view = View.inflate(this, R.layout.dialog_login, null);

        final EditText etUser = (EditText) view.findViewById(R.id.et_user);
        final EditText etPassword = (EditText) view.findViewById(R.id.et_password);

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setView(view)
                .setPositiveButton(getResources().getString(R.string.btn_login), null)
                .setNegativeButton(getResources().getString(R.string.btn_clear), null);

        AlertDialog alertDialog = builder.create();

        DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    finish();

                    return true;
                }
                return false;
            }
        };

        alertDialog.setOnKeyListener(onKeyListener);

        alertDialog.setCancelable(false);

        alertDialog.show();

        alertDialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String user = etUser.getText().toString();
                String password = etPassword.getText().toString();

                Log.e(TAG, "onClick: user = " + user + " password = " + password);
                Toast.makeText(getApplicationContext(), "user = " + user + " password = " + password, Toast.LENGTH_SHORT).show();
            }
        });

        alertDialog.getButton(Dialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etUser.setText(null);
                etPassword.setText(null);
            }
        });
    }
}
